﻿using UnityEngine;
using UnityEditor;

namespace CWM.Skinn
{
    public static partial class SkinnContextCommands
    {
        public static partial class ToolTips
        {
            public const string CombineBones = "Combine one bone's weights into another bone's weights.";
        }

        [CtxMenuItem("SkinnedMeshRenderer/Bones/Combine Bones", ToolTips.CombineBones, ContextFlag.BoneBone, 001)]
        public static void SkinnedMeshRendererCombineBones()
        {
            var boneContext0 = SkinnEx.FindGameObject(SkinnContext.ContextBone0);
            var boneContext1 = SkinnEx.FindGameObject(SkinnContext.ContextBone1);

            if (!boneContext0 || !boneContext1)
            {
                Debug.LogError(boneContext0); Debug.LogError(boneContext1);
                return;
            }

            foreach (var item in SkinnContext.GetContextItems())
            {
                var context = item.GetComponent<SkinnedMeshRenderer>();
                if (SkinnEx.IsNullOrNotInAScene(context)) continue;

                SkinnedMeshRenderer newAsset;
                SkinnEx.CloneRemoveBones(context, new Transform[] { boneContext1.transform }, boneContext0.transform, out newAsset);
                if (newAsset)
                {
                    Undo.RegisterCompleteObjectUndo(context, "Combine Bones");

                    context.sharedMesh = newAsset.sharedMesh;
                    context.rootBone = newAsset.rootBone;
                    context.bones = newAsset.bones;
                    context.SetBounds();
                    SkinnEx.Release(newAsset.gameObject);
                }
            }
            SkinnContext.Finished();
        }
    }
}